<?php
// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Web Services Payment" and licensed under
// the terms of the GNU Affero General Public License version 3, or (at your
// option) a later version. You should have received a copy of this license
// along with the software. If not, see <https://www.gnu.org/licenses/>.

namespace Hawese\Payment\Support;

use Nyholm\Psr7\Factory\Psr17Factory as Psr17UriFactory;
use Psr\Http\Message\ResponseInterface;

class Http
{
    /**
     * For GET requests, spaces are percent encoded (%20)
     *
     * @param array $queryParams associative array.
     */
    public static function buildUriQuery(array $queryParams): string
    {
        return http_build_query($queryParams, '', '&', PHP_QUERY_RFC3986);
    }

    /**
     * For application/x-www-form-urlencoded, spaces are encoded as + signs
     */
    public static function buildFormQuery(array $bodyParams): string
    {
        return http_build_query($bodyParams, '', '&', PHP_QUERY_RFC1738);
    }

    public static function getJsonBody(ResponseInterface &$response): object
    {
        return json_decode((string) $response->getBody());
    }

    public static function appendQueryParams(
        string $url,
        array $queryParams
    ): string {
        $uri = (new Psr17UriFactory())->createUri($url);
        $urlQueryString = $uri->getQuery();
        $queryParamsString = self::buildUriQuery($queryParams);

        return (string) $uri->withQuery(
            empty($urlQueryString)
            ? $queryParamsString
            : "$urlQueryString&$UqueryParams"
        );
    }
}
